// // import { XController, XJsonController } from '../../../lib/helper';
// // import { Get, Render, Post, Controller } from 'routing-controllers';

import { V, Connection, ExpressContext } from 'x-engine';
import { Response } from "express";
import { X, FindOption, FetchOption } from 'x-orm';
import { ProxyUser } from '../ml/proxy_user';
import { strtotime, date } from 'locutus/php/datetime';
import { caipiao, COrderStatus } from '../../../collect';
import { ProxyMember } from '../ml/proxy_member';
import { BindAccount } from '../ml/bind_account';
import { SetCache, getTerm } from '../../../lib/utils';
import { VrOrder } from '../ml/order';
import { ProxyCash } from '../ml/proxy_cash';

const goods50 = 232;
const goods100 = 233;

@V.Controller({
    type: Connection.HTTP,
    url: "/proxy",
})
export class MainProxy {
    index(
        res: Response,
    ) {
        res.redirect("/proxy/index.html");
    }
}

function common(ctx : ExpressContext){
    if(ctx.req.query.skin){
        ctx.req.cookies.skin = ctx.req.query.skin;
    }
    if(ctx.req.cookies.skin){
        return {
            skin : ctx.req.cookies.skin
        }
    }
    else{
        return {
            skin : 'black'
        }
    }
}

@V.Controller({
    type: Connection.HTTP,
    url: "/proxy/:method.html",
    authorization: ['proxy'],
    render: "proxy/:method.html",
    common : common
})
export class MainProxy2 {

    index() {

    }

    main(res: Response) {
    }

    async zonghe(
        proxyUser: ProxyUser,
        nickname?,
        start_time?,
        end_time?
    ) {
        const listOption: any = {};
        /**
         * 经济会员位于所有我的下属综合会员加上我的直属经济会员
         */
        const _data = await this._buildProxyOption(listOption, 'normal', [], nickname, start_time, end_time, 1);
        listOption.where.parent_id = 1;
        // console.log(listOption)
        const list = await X.of(ProxyUser).find(listOption);

        return {
            // children,
            list,
            ..._data,
            proxy: proxyUser,
            type: "zonghe"
            // nickname : nickname,
            // start_time : start_time,
            // end_time : end_time
        }
    }

    async jingji(proxyUser: ProxyUser, nickname?, start_time?, end_time?, parent_id?) {
        //取出我所有的综合会员以及经济会员
        const option: FindOption<ProxyUser> = {
            where: {
                parent_id: proxyUser.id,
                type: "normal"
            },
        };
        const children = await X.of(ProxyUser).find(option);
        if (proxyUser.type == 'normal') {
            children.push(proxyUser);
        }
        //console.log(children) 
        const listOption = {};
        /**
         * 经济会员位于所有我的下属综合会员加上我的直属经济会员
         */
        const _data = await this._buildProxyOption(listOption, 'jingji', children, nickname, start_time, end_time, parent_id);

        const list = await X.of(ProxyUser).find(listOption);

        return {
            children,
            list,
            ..._data,
            proxy: proxyUser,
            type: "jingji"
            // nickname : nickname,
            // start_time : start_time,
            // end_time : end_time
        }
    }


    async jigou(proxyUser: ProxyUser, nickname?, start_time?, end_time?, parent_id?) {
        let data = await this.jingji(proxyUser);

        if (proxyUser.type == 'jingji') {
            data.list.push(proxyUser);
        }

        //机构
        const option = {};
        const _data = this._buildProxyOption(option, 'jigou', data.list, nickname, start_time, end_time, parent_id);
        // console.log(JSON.stringify(option));
        // const option : FindOption<ProxyUser> = {
        //     where : {
        //         type : "jigou",
        //         parent_id : ['in',data.list.map(item => item.id)]
        //     }
        // };
        // if(nickname){
        //     option.where.nickname = ['like','%'+nickname+'%']; 
        // }
        // if(!start_time){
        //     start_time = "1970-01-01";
        // }
        // if(!end_time){
        //     end_time = "2099-01-01";
        // }
        // option.where.add_time = ['between',strtotime(start_time),strtotime(end_time)];
        const jigous = await X.of(ProxyUser).find(option);

        data.children = data.list;



        data.list = jigous;
        data = Object.assign(data, _data);
        data.type = 'jigou';

        return data;

        //机构
        // const data : any = {};
        // data.children = jingjis;
        // data.list = jigous;
        // return data;
    }
    async jujian(
        proxyUser: ProxyUser,
        nickname?,
        start_time?,
        end_time?,
        parent_id?
    ) {
        let data = await this.jigou(proxyUser);
        if (proxyUser.type == 'jigou') {
            data.list.push(proxyUser);
        }
        console.log(parent_id)
        const option = {};
        const _data = this._buildProxyOption(option, 'jujian', data.list, nickname, start_time, end_time, parent_id);
        const jujians = await X.of(ProxyUser).find(option);

        data.children = data.list;

        data.list = jujians;
        data = Object.assign(data, _data);
        data.type = 'jujian';

        return data;
    }

    async _buildProxyOption(option: FindOption<ProxyUser>, type, list: ProxyUser[], nickname, start_time, end_time, parent_id) {
        option.where = {
            type,
            parent_id: ['in', list.map(item => item.id)]
        }
        //
        if (parent_id) {
            let _parent = await X.of(ProxyUser).findOne(parent_id);
            if (_parent) {
                let _children = await this._getAllChildren(_parent);
                option.where.parent_id = ['in', _children.map(item => item.id)];
            }
        }
        option.addon = {
            parent: true
        }
        if (nickname) {
            option.where.nickname = ['like', '%' + nickname + '%'];
        }
        if (!start_time) {
            start_time = "1970-01-01";
        }
        if (!end_time) {
            end_time = "2099-01-01";
        }
        option.where.add_time = ['between', strtotime(start_time), strtotime(end_time)];
        return {
            nickname,
            start_time,
            end_time,
            parent_id
        }
    }


    async addJingji(proxyUser: ProxyUser, id: number, type) {
        const option: FindOption<ProxyUser> = {
            where: {
                parent_id: proxyUser.id,
                type: "normal"
            },
        };
        let children: ProxyUser[];
        if (type == 'jigou') {
            children = (await this.jigou(proxyUser)).children;
        }
        else if (type == 'jingji') {
            children = (await this.jingji(proxyUser)).children;
        }
        else if (type == 'jujian') {
            children = (await this.jujian(proxyUser)).children;
        }
        else if (type == 'normal') {
            children = [];
        }
        else {
            return;
        }
        // const children = await X.of(ProxyUser).find(option);
        // children.push(proxyUser); 

        const data: any = {
            children
        }
        //编辑模式
        if (id) {
            //是否是我的会员
            let info = await X.of(ProxyUser).findOne(id);
            if (!info) {
                return;
            }
            if (!this._belongsTo(info, proxyUser)) {
                return;
            }

            data.info = info;
        }
        data.type = type;
        return data;
    }



    /**
     * 客户管理
     */
    async clients(
        proxyUser: ProxyUser,
        phone?,
        nickname?,
        start_time?,
        end_time?,

        zhishu?,
        parent_id?,
        page?

    ) {
        let children = await this._getAllChildren(proxyUser);
        children.unshift(proxyUser);

        const option: FindOption<ProxyMember> = {
            where: {

            },
            addon: {
                parent: 1,
                member :1
            }
        };

        let list;
        let count = 0;

        try {
            /**
             * 查询条件处理
             */
            if (phone) {
                option.where.phone = phone;
            }
            if (nickname) {
                option.where.nickname = ['like', '%' + nickname + '%']
            }
            if (!start_time) {
                start_time = '1970-01-01';
            }
            if (!end_time) {
                end_time = '2099-01-01';
            }
            option.where.add_time = ['between', strtotime(start_time), strtotime(end_time)];
            let _children: ProxyUser[];
            if (parent_id) {
                let _parent = await X.of(ProxyUser).findOne(parent_id);
                if (zhishu) {
                    _children = await this._getChildren(_parent);
                }
                else {
                    _children = await this._getAllChildren(_parent);
                }
                _children.push(_parent);
            }
            else {
                _children = await this._getAllChildren(proxyUser);
                _children.push(proxyUser);
            }
            option.where.parent_id = ['in', _children.map(item => item.id)];
            option.order = {
                add_time: "desc"
            };

            if (!page) {
                page = 1;
            }

            count = await X.of(ProxyMember).count(option);
            option.limit = [(page - 1) * 20, 20];

            list = await X.of(ProxyMember).find(option);
        }
        catch (e) {
            list = [];
        }

        return {
            children,
            list,
            nickname,
            phone,
            start_time,
            end_time,
            parent_id,
            zhishu,
            count,
            page,
            proxy: proxyUser
        }
    }

    /**
     * 查看用户详情
     */
    async member_detail(
        id?
    ) {
        const memberInfo = await X.of(ProxyMember).findOne({
            where : {
                id : id,
            },
            addon : {
                member : 1
            }
        });
        return {
            info: memberInfo
        };
    }

    async addMember() {

    }

    /**
     * 权限管理
     */
    permission() {

    }

    /**
     * 保证金监控
     */
    async baozheng(
        proxyUser: ProxyUser
    ) {
        let children = await this._getAllChildren(proxyUser);
        children.push(proxyUser);
        let option: FindOption<VrOrder> = {
            where: {
                from_proxy: {
                    in: children.map(item => item.id)
                },
                order_state: {
                    get: 20
                }
            }
        };
        let term = getTerm();
        let ret;

        term -= 1;

        let count = async (index,item) => {
            let _option = {...option};
            if(index == 0){
                _option.where.term = term;
            }
            else{
                _option.where.term = {
                    slike : date("Ymd") 
                }
            }
            //dan
            _option.where.guess = 'single';
            let single = await X.of(VrOrder).count(_option);
            //shuang
            _option.where.guess = 'double';
            let double = await X.of(VrOrder).count(_option);
            //zong
            let zong = single + double;

            return {
                single,
                double,
                zong
            };
        };

        ret = [];
        for(const index of [0,1]){
            let arr = []
            for(const item of [goods50,goods100]){
                let r = await count(index,item);
                arr.push(r);
            }
            ret.push(arr);
        }

        // console.log(ret);

        // ret = await Promise.all([0,1,2].map(async index => {
        //     return await Promise.all([goods50, goods100].map(async item => {
                
        //     }));
        // }));

        // console.log(ret)

        // let ret = await Promise.all([goods50,goods100].map(async item => {
        //     //dan
        //     option.where.guess = 'single';
        //     let single = await X.of(VrOrder).count(option);
        //     //shuang
        //     option.where.guess = 'double';
        //     let double = await X.of(VrOrder).count(option);
        //     //zong
        //     let zong = single + double;

        //     return {
        //         single,
        //         double,
        //         zong
        //     };
        // }));

        return {
            info: proxyUser,
            ret
        }
    }

    /**
     * 加盟商监控
     */
    async jiameng(
        proxyUser: ProxyUser,
        type?,
        nickname?
    ) {
        let list, list1, list2;
        if (type == 'normal' || !type) {
            list = list1 = (await this.jingji(proxyUser, nickname)).children;
            // console.log(list1);
        }
        if (type == 'jingji' || !type) {
            list = list2 = (await this.jigou(proxyUser, nickname)).children;
        }

        if (!type) {
            list = list1.concat(list2);
        }

        return {
            list,
            nickname,
            type
        }
    }


    /**
     * 个人客户风控
     */
    async fengkong(
        proxyUser: ProxyUser,
        phone?,
        nickname?,
        page?
    ) {
        if (!page) page = 1;
        const children = await this._getAllChildren(proxyUser);
        children.push(proxyUser);

        const option: FindOption<ProxyMember> = {
            where: {
                parent_id: ['in', children.map(item => item.id)]
            },
            addon: {
                parent: 1
            },
        };
        if (phone) {
            option.where.phone = phone;
        }
        if (nickname) {
            option.where.nickname = ['like', "%" + nickname + "%"];
        }

        let list: ProxyMember[];
        let count = 0;
        let today = strtotime(date("Y-m-d"));
        try {
            count = await X.of(ProxyMember).count(option);
            option.limit = [(page - 1) * 20, 20];
            list = await X.of(ProxyMember).find(option);

            for (const item of list) {
                let w = ` add_time between ${today} and ${today + 24 * 3600} and buyer_phone = '${item.phone}' `;
                let sql = `select (count(*) / (select count(*) from nw_vr_order where ${w})) as rate from nw_vr_order where ${w} and caipiao_status > 20`;
                let res = await X.query(sql);
                // console.log(res);
                (item as any).day_rate = Math.floor((res[0] as any).rate * 100);
                sql = `
                    select ifnull(sum(order_amount),0) as mm from nw_vr_order where ${w} 
                `;
                res = await X.query(sql);
                (item as any).mm = (res[0] as any).mm;
                sql = `select (count(*) / (select count(*) from nw_vr_order where buyer_phone = '${item.phone}')) as rate from nw_vr_order where buyer_phone = '${item.phone}' and caipiao_status > 20`;
                res = await X.query(sql);
                (item as any).total_rate = Math.floor((res[0] as any).rate * 100);
            }
        }
        catch (e) {

        }

        return {
            list,
            children,
            page,
            nickname,
            phone,
            count,
        }

    }

    /**
     * 彩票信息
     */
    async caipiao(
        proxyUser: ProxyUser,
        type?,
        start_time?,
        end_time?,
        id?,
        page?
    ) {
        if (!type) {
            type = 'cqssc';
        }
        const option: FindOption<caipiao> = {
            where: {
                type,
            },
            order: {
                open_time: 'desc'
            }
        };
        if (!start_time) {
            start_time = "1970-01-01";
        }
        if (!end_time) {
            end_time = "2099-01-01";
        }
        if (id) {
            option.where.id = ['like', '%' + id + '%'];
        }
        if (!page) {
            page = 1;
        }

        option.where.open_time = ['between', strtotime(start_time), strtotime(end_time)];
        const count = await X.of(caipiao).count(option);
        const start = (page - 1) * 20;
        option.limit = [start, 20];
        const list = await X.of(caipiao).find(option);
        // console.log(count)
        return {
            list,
            start_time,
            end_time,
            id,
            count,
            page
        }



    }

    /**
     * 订单列表
     */
    async order_list(
        proxyUser: ProxyUser,
        phone?,
        start_time?,
        end_time?,
        winType?,
        status?,
        parent_id?,
        page?
    ) {
        if (!page) {
            page = 1;
        }
        const children = await this._getAllChildren(proxyUser);
        children.push(proxyUser);

        const option: FetchOption<VrOrder> = {
            where: {
                from_proxy: {
                    in: children.map(item => item.id)
                },
                order_state: {
                    gt: 10
                }
            },
            page: page,
            addon: {
                proxy_member: true,
                proxy_parent: true,
            }
        }

        if (!start_time) {
            start_time = '1970-01-01';
        }
        if (!end_time) {
            end_time = '2099-01-01';
        }
        option.where.add_time = {
            let: strtotime(end_time),
            get: strtotime(start_time)
        };
        //手机号
        if (phone) {
            option.where.buyer_phone = phone;
        }
        //所属
        if (parent_id) {
            option.where.from_proxy = parent_id;
        }
        //胜负
        if (winType == 'win') {
            option.where.caipiao_status = { get: COrderStatus.win };
        }
        else if (winType == 'lose') {
            option.where.caipiao_status = COrderStatus.lose
        }
        else {
            option.where.caipiao_status = {
                get: COrderStatus.notopen
            }
        }
        if (status == 'gotten') {
            option.where.and = {
                caipiao_status: COrderStatus.gotten
            }
        }
        let [list, count] = await X.of(VrOrder).fetch(option);
        return {
            children,
            phone,
            start_time,
            end_time,
            winType,
            status,
            parent_id,
            list,
            count,
            page
        }
    }

    /**
     * 交易汇总
     * @param child 
     * @param parent 
     */
    async huizong(
        proxyUser: ProxyUser
    ) {
        //
        let today = strtotime(date("Y-m-d"));

        let children = await this._getAllChildren(proxyUser);
        children.push(proxyUser);
        let newcount = await X.of(ProxyMember).count({
            where: {
                parent_id: {
                    in: children.map(item => item.id)
                },
                add_time: {
                    let: today + 24 * 3600,
                    get: today
                }
            },
        });

        let ordercount = await X.of(VrOrder).find({
            extFields: {
                count: {
                    order_id: "count"
                },
                sum: {
                    order_amount: 'total',
                    goods_num: "goods_nums",
                    s_fee: "s_fees"
                }
            },
            where: {
                add_time: {
                    let: today + 24 * 3600,
                    get: today
                },
                from_proxy: {
                    in: children.map(item => item.id)
                }
            }
        });

        //中奖金额
        let winMoney = await X.of(VrOrder).find({
            extFields: {
                sum: {
                    order_amount: 'total',
                    s_fee: 'sfee',
                    f_fee: 'ffee'
                }
            },
            where: {
                add_time: {
                    let: today + 24 * 3600,
                    get: today
                },
                from_proxy: {
                    in: children.map(item => item.id)
                },
                caipiao_status: {
                    get: COrderStatus.win
                }
            }
        });
        let win: any = winMoney[0];
        // console.log(winMoney)

        //没中奖
        let loseMoney = await X.of(VrOrder).find({
            extFields: {
                sum: {
                    order_amount: 'total',
                    s_fee: 'sfee',
                    f_fee: 'ffee'
                }
            },
            where: {
                add_time: {
                    let: today + 24 * 3600,
                    get: today
                },
                from_proxy: {
                    in: children.map(item => item.id)
                },
                caipiao_status: COrderStatus.lose
            }
        });
        let lose: any = loseMoney[0];

        return {
            newcount,
            order: ordercount[0],
            result: (win.total - win.sfee - win.ffee) - (lose.total - lose.sfee - lose.ffee)
        }
    }


    /**
     * 成交报表
     */
    async chengjiao() {

    }
    /**
     * 开奖统计
     */
    async kaijiang(
        proxyUser: ProxyUser,
        phone?,
        start_time?,
        end_time?,
        page?
    ) {
        let children = await this._getAllChildren(proxyUser);
        const phones = await X.of(ProxyMember).find({
            where: {
                parent_id: ['in', children.map(item => item.id)]
            }
        });

        let list: VrOrder[];

        do {
            if (!start_time || !end_time) {
                break;
            }
            const option: FindOption<VrOrder> = {
                where: {
                    caipiao_type: 'cqssc',
                    caipiao_status: {
                        gt: COrderStatus.notopen
                    }
                    // buyer_phone : ['in',phones.map(item => item.phone)]
                },
                addon: {
                    proxy_member: true
                }
            };

            if (phone) {
                option.where.buyer_phone = phone;
            }
            else if (phones.length) {
                option.where.buyer_phone = ['in', phones.map(item => item.phone)];
            }

            option.where.add_time = {
                let: strtotime(end_time),
                get: strtotime(start_time)
            };
            if (phones.length) {
                list = await X.of(VrOrder).find(option);
                console.log(option)
                await Promise.all(list.map(async item => {
                    await X.makeAddon(item.proxy_member, 'parent');
                }));

                //聚合数据
                const cache: any = {};
                list.forEach(item => {
                    const time = date("Y-m-d", item.add_time);
                    let index = time + item.buyer_phone;
                    let target = cache[index] = cache[index] || item;
                    //整合数据
                    target.n50 = target.n50 || 0;
                    target.n100 = target.n100 || 0;
                    target.t50 = target.t50 || 0;
                    target.t100 = target.t100 || 0;
                    target.total = target.total || 0;
                    target.zhong = target.zhong || 0;
                    target.nozhong = target.nozhong || 0;
                    target.stat = target.stat || 0;
                    cache[index] = target;
                    if (item.goods_id == goods50) {
                        target.n50 += item.goods_num;
                        target.t50 += item.order_amount;
                    }
                    if (item.goods_id == goods100) {
                        target.n100 += item.goods_num;
                        target.t100 += item.order_amount;
                    }
                    if (item.caipiao_status == COrderStatus.lose) {
                        target.nozhong += item.goods_num;
                        target.stat -= (item.order_amount - item.f_fee - item.s_fee);
                    }
                    else if (item.caipiao_status >= COrderStatus.win) {
                        target.zhong += item.goods_num;
                        target.stat += (item.order_amount - item.f_fee - item.s_fee);
                    }
                    target.total += item.order_amount;
                    if (target.zhong + target.nozhong == 0) {
                        target.winrate = 0;
                    }
                    else {
                        target.winrate = Math.floor(target.zhong / (target.nozhong + target.zhong));
                    }

                    // cache[index].push(item);
                });
                list = Object.values(cache);
            }
            else {
                list = [];
            }
            //50
            // const sql = `
            //     select 
            //         FROM_UNIXTIME(add_time,'%Y-%c-%d') as time, o.*
            //     from nw_vr_order o
            //     where 
            //         caipiao_type = 'cqssc' and
            //         add_time between ${strtotime(start_time)} and ${strtotime(end_time)} and
            //         buyer_phone in (${phones.map(item => `'${item.phone}'`).join(",")}) and
            //         goods_id = $gid
            //     group by time
            // `;
            // //50
            // let list1 = await X.query(sql.replace("$gid",goods50 + ""));
            // let list2 = await X.query(sql.replace("$gid",goods100 + ''));
            // //整理数据

            // console.log(sql);
            // // list = await X.query(sql);

        } while (0);

        // if(!page){
        //     page = 1;
        // }



        return {
            phone,
            start_time,
            end_time,
            page,
            // count,
            list
        }
    }
    /**
     * 订货统计
     */
    async dinghuo(
        proxyUser: ProxyUser,
        phone?,
        start_time?,
        end_time?
    ) {
        let children = await this._getAllChildren(proxyUser);
        const phones = await X.of(ProxyMember).find({
            where: {
                parent_id: ['in', children.map(item => item.id)]
            }
        });

        let list: VrOrder[] = [];
        do {
            if (!start_time || !end_time) {
                break;
            }
            const option: FindOption<VrOrder> = {
                where: {
                    caipiao_type: 'cqssc',
                    caipiao_status: {
                        gt: COrderStatus.notopen
                    }
                    // buyer_phone : ['in',phones.map(item => item.phone)]
                },
                addon: {
                    proxy_member: true
                }
            };

            if (phone) {
                option.where.buyer_phone = phone;
            }
            else if (phones.length) {
                option.where.buyer_phone = ['in', phones.map(item => item.phone)];
            }

            option.where.add_time = {
                let: strtotime(end_time),
                get: strtotime(start_time)
            };

            if (phones.length) {
                list = await X.of(VrOrder).find(option);
                await Promise.all(list.map(async item => {
                    await X.makeAddon(item.proxy_member, 'parent');
                }));
            }

        } while (0);

        return {
            phone,
            start_time,
            end_time,
            list,
            goods50,
            goods100
        }
    }

    /**
     * 签约
     */
    async qianyue(
        proxyUser: ProxyUser
    ) {
        //检查是否签约
        const info = await X.of(BindAccount).findOne({
            where: {
                proxy_id: proxyUser.id
            }
        });

        return {
            info
        }
    }

    /**
     * 出金
     * @param child 
     * @param parent 
     */
    async chujin(
        proxyUser: ProxyUser,
        start_time?,
        end_time?,
        page?
    ) {
        if(!start_time){
            start_time = '1970-01-01';
        }
        if(!end_time){
            end_time = '2099-01-01';
        }
        //查询签约记录
        const info = await X.of(BindAccount).findOne({
            where: {
                proxy_id: proxyUser.id
            }
        });

        const [list,count] = await X.of(ProxyCash).fetch({
            where : {
                proxy_id : proxyUser.id,
                add_time : {
                    between : [strtotime(start_time),strtotime(end_time)]
                }
            },
            page : page,
            order : {
                add_time : 'desc'
            }
        });

        return {
            list,
            count,
            info: info,
            proxy: proxyUser,
            page,
            start_time,
            end_time,
            limit :proxyUser.money - proxyUser.limit_money - proxyUser.dj_money
        }

    }

    /**
     * 添加提现请求
     */
    async add_cash(
        proxyUser :ProxyUser,
        
    ){
        return {
            limit : proxyUser.money - proxyUser.limit_money - proxyUser.dj_money,
        }
    }


    /**
     * 代理商转移列表
     */
    async transfer(
        proxyUser: ProxyUser,
        id: number,
        type?
    ) {
        if (type == 'member') {
            let member = await X.of(ProxyMember).findOne(id);
            if (!member) {
                return;
            }
            let children = await this._getAllChildren(proxyUser);
            return {
                proxy: member,
                children,
                type
            }
        }
        else if (type == 'proxy') {
            let proxy = await X.of(ProxyUser).findOne(id);
            if (!proxy) {
                return;
            }
            await X.makeAddon(proxy, 'parent');
            await X.makeAddon(proxy.parent, 'parent')
            // console.log(proxy.parent.parent)
            await X.makeAddon(proxy.parent.parent, 'children');
            return {
                proxy,
                children: proxy.parent.parent.children,
                type
            }
        }

    }

    /**
     * 管理员出金列表
     */
    async cash_list(
        proxyUser : ProxyUser,
        page?,
        status?
    ){
        if(!page){
            page = 1;
        }
        if(proxyUser.id !== 1){
            return;
        }
        console.log(status,page)
        let [list,count] = await X.of(ProxyCash).fetch({
            where : {
                status : (() => {
                    return status == -1 ? {
                        gt : -1
                    } : status
                })()
            },
            page : page,
            addon : {
                proxy : true,
                bindAccount : true
            }
        });

        return {
            list,count,page,status
        }
    }


    /**
     * 
     */
    async profile(proxyUser: ProxyUser) {

        return {
            proxy: proxyUser
        }
    }

    async logout(req, res: Response) {
        await SetCache("proxy:token:" + req.session.proxy_token, "-1");
        res.redirect("/proxy");
    }



    async _belongsTo(child: ProxyUser, parent: ProxyUser) {
        let loop = child;
        let flag = false;
        while (loop && loop.parent_id > 0) {
            // console.log(loop)
            if (loop.parent_id == parent.id) {
                flag = true;
            }
            await X.makeAddon(loop, 'parent');
            loop = loop.parent;
        }
        return flag;
    }

    /**
     * 得到直属下级会员
     */
    async _getChildren(proxyUser: ProxyUser) {
        await X.makeAddon(proxyUser, 'children');
        return proxyUser.children;
    }

    /**
     * 得到所有下级会员
     */
    async _getAllChildren(proxyUser: ProxyUser, includeSelf = false) {
        let children = await this._getChildren(proxyUser);
        let result = children;
        for (let i = 0; i < children.length; i++) {
            result = result.concat(await this._getAllChildren(children[i]));
        }
        return result;
    }



}

//登录不需要授权，比较特殊
@V.Controller({
    type: Connection.HTTP,
    url: "/proxy/:method.html",
    render: "proxy/:method.html",
    common : common
})
export class ProxyLogin {
    login() {
    }

}
